package both;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * Read the server's question list file.
 */

public class QuestionFileReader {

	public static ArrayList<Question> readQuestionNodes(NodeList nodes) throws JAXBException {
		JAXBContext jaxbContext = JAXBContext.newInstance(Question.class);
		Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		ArrayList<Question> ret = new ArrayList<Question>(nodes.getLength());
		for (int i = 0; i < nodes.getLength(); i++) {
			ret.add((Question) jaxbUnmarshaller.unmarshal(nodes.item(i)));
		}
		return ret;
	}

	public static ArrayList<Question> readQuestionsFile(File questionFile) throws ParserConfigurationException, SAXException, IOException, JAXBException {
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		NodeList nodes = dBuilder.parse(questionFile).getElementsByTagName("question");
		return readQuestionNodes(nodes);

	}

	public static void main(String[] args) throws Exception {
		File fXmlFile = new File("src/testquestions.xml");
                ArrayList<Question> result = readQuestionsFile(fXmlFile);
		System.out.println(result);
	}
}
